package vip.zhenzicheng.test.juc.threadlocal;

import lombok.extern.slf4j.Slf4j;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 5个销售卖房子，只关心最终总销量准确计数
 *
 * @author zhenzicheng
 * @date 2022-09-08 11:35
 */
@Slf4j
public class ThreadLocalCase {

  public static void main(String[] args) {
    House house = new House();
    for (int i = 0; i < 5; i++) {
      new Thread(() -> {
        int size = new Random().nextInt(5) + 1;
        try {
          for (int j = 0; j < size; j++) {
            house.saleHouse();
            house.saleVolumeByThreadLocal();
          }
          log.info("{} 号销售出: {}", Thread.currentThread().getName(), house.saleVolume.get());
        } finally {
          house.saleVolume.remove();
        }
      }, String.valueOf(i)).start();

      try {
        TimeUnit.MILLISECONDS.sleep(300);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    log.info("总销售为: {}", house.saleCount);
  }
}

class House {

  /**
   * 创建并初始化ThreadLocal
   */
  final ThreadLocal<Integer> saleVolume = ThreadLocal.withInitial(() -> 0);

  int saleCount = 0;

  // 原始加锁方式
  public synchronized void saleHouse() {
    ++saleCount;
  }

  // 使用ThreadLocal
  public void saleVolumeByThreadLocal() {
    saleVolume.set(saleVolume.get() + 1);
  }
}
